<template>
  <div class="form-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="互助标题" prop="helpTitle">
            <el-input v-model="ruleForm.helpTitle"></el-input>
          </el-form-item>
          <el-form-item label="互助类别" prop="helpClassification">
            <el-select
              v-model="ruleForm.classificationName"
              clearable
              placeholder="请选择"
              style="width: 330px"
              @change="setClassification(ruleForm.classificationName * 1)"
            >
              <el-option
                v-for="item in classificationList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="有效期限" prop="endTime">
            <el-date-picker
              v-model="ruleForm.endTime"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="有效区域" prop="effectiveArea" size="mini">
            <!-- 省市区级联选择器 -->
            <el-cascader
              v-model="selectedOptions"
              size="mini"
              :options="options"
              clearable
              style="width: 250px"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item label="是否置顶" prop="postTop">
            <el-select v-model="ruleForm.postTop" clearable placeholder="置顶">
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="row" label="用户ID">
            <el-input v-model="ruleForm.userId" disabled="false"></el-input>
          </el-form-item>
          <!-- 内容 -->
          <el-form-item label="详细描述" prop="detailedDescription">
            <el-col :span="100" style="margin-left: -10px">
              <editor
                v-model="ruleForm.detailedDescription"
                :min-height="192"
                style="width: 800px"
              />
            </el-col>
          </el-form-item>

          <!-- 图片 -->
          <el-form-item label="图片">
            <el-upload
              action="http://192.168.137.1:9090/alumni-circle/api/photo/uploadImg"
              multiple
              list-type="picture-card"
              :data="fileData"
              :file-list="fileList"
              name="image"
              accept="image/jpeg,image/png,image/jpg"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleimg"
            >
              <i class="el-icon-plus"></i>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传jpg/png/jpeg文件，且单个不超过2M
                </div>
              </template>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>

          <el-form-item style="margin-top: 20px">
            <el-button type="primary" @click="submitForm('ruleForm')">
              提交
            </el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {
    classificationSelectView,
    helpUpdate,
    helpAdd,
  } from '../../api/management/management'
  // 导入省市区数据组件
  import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
  //富文本
  import Editor from '@/components/Editor'
  export default {
    name: 'EditHelp',
    components: {
      Editor,
    },
    data() {
      return {
        ruleForm: {
          imageUrlList: [],
          helpTitle: '',
          helpClassification: '',
          endTime: '',
          detailedDescription: '',
          postTop: '',
          effectiveArea: '',
        },
        rules: {
          helpTitle: [
            { required: true, message: '请输入标题', trigger: 'blur' },
          ],
          helpClassification: [
            { required: true, message: '请选择类别', trigger: 'change' },
          ],
          endTime: [
            {
              required: true,
              message: '请选择有效期限（限制两个月内）',
              trigger: 'change',
            },
          ],
          detailedDescription: [
            { required: true, message: '请选择详细描述', trigger: 'change' },
          ],
          postTop: [
            { required: true, message: '请选择置顶', trigger: 'change' },
          ],
          effectiveArea: [
            { required: true, message: '请选择限制区域', trigger: 'change' },
          ],
        },
        classificationList: {},
        //时间选择器
        pickerOptions: {
          disabledDate(time) {
            //最大期限 后推两个月 60天算
            return time.getTime() > Date.now() + 3600 * 1000 * 24 * 60
          },
          shortcuts: [
            {
              text: '今天',
              onClick(picker) {
                picker.$emit('pick', new Date())
              },
            },
            {
              text: '昨天',
              onClick(picker) {
                const date = new Date()
                date.setTime(date.getTime() - 3600 * 1000 * 24)
                picker.$emit('pick', date)
              },
            },
            {
              text: '一周前',
              onClick(picker) {
                const date = new Date()
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
                picker.$emit('pick', date)
              },
            },
          ],
        },
        // 将省市区数据赋给级联选择器
        options: regionData,
        // 存放用户选择后省市区的信息
        selectedOptions: [],
        //图片上传
        fileList: [],
        dialogVisible: false,
        dialogImageUrl: '',
        fileData: {
          // 额外参数
          id: '',
        },
      }
    },
    created() {
      this.row = this.$route.query.row
      if (this.row) {
        this.ruleForm = this.row
        //赋值地区
        this.selectedOptions =
          TextToCode[this.ruleForm.effectiveArea.split('-')[0]][
            this.ruleForm.effectiveArea.split('-')[1]
          ][this.ruleForm.effectiveArea.split('-')[2]].code
        //赋值图片List
        this.ruleForm.imageUrlList.forEach((res, index) => {
          const params = {
            name: index,
            url: res,
          }
          this.fileList.push(params)
        })
      }
      this.getClassificationList()
    },
    methods: {
      // 省市区级联选择器选择后更新用户前端
      handleChange(value) {
        for (let i = 0; i < this.selectedOptions.length; i++) {
          if (i === 0) {
            const province = CodeToText[this.selectedOptions[i]]
            this.ruleForm.effectiveArea = province
          }
          if (i === 1) {
            const city = CodeToText[this.selectedOptions[i]]
            this.ruleForm.effectiveArea += '-' + city
          }
          if (i === 2) {
            const country = CodeToText[this.selectedOptions[i]]
            this.ruleForm.effectiveArea += '-' + country
          }
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //封装图片urlList
            this.ruleForm.imageUrlList = [] //置空，否则出现重复
            this.fileList.forEach((res) => {
              if (res.response != null) {
                this.ruleForm.imageUrlList.push(res.response.data)
              } else {
                this.ruleForm.imageUrlList.push(res.url)
              }
            })
            //判断 编辑 or 添加
            if (this.row) {
              helpUpdate(this.ruleForm).then((res) => {
                if (res.code == 200) {
                  this.$baseMessage('修改成功', 'success')
                } else {
                  this.$baseMessage('修改失败', 'error')
                }
              })
            } else {
              helpAdd(this.ruleForm).then((res) => {
                if (res.code == 200) {
                  this.$baseMessage('添加成功', 'success')
                  this.$router.push('/helpManagement/index')
                } else {
                  this.$baseMessage('添加失败', 'error')
                }
              })
            }
          } else {
            return false
          }
        })
      },
      //重置
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      // 图片上传

      handleRemove(image, fileList) {
        console.log('删除', image, fileList)
        this.fileList = fileList
        //七牛云上删除
      },
      handlePictureCardPreview(image) {
        //这里需要注意 用的img并不是file，因为接口文档给的是img，我们在upload中定义个name=“img”参数就可以了
        // 检查文件类型
        const isImage = image.raw.type.includes('image')
        if (!isImage) {
          this.$message.error('上传文件类型必须是图片!')
          return false
        }
        // 检查文件大小
        if (image.size > 2 * 1024 * 1024) {
          this.$message.error(`上传文件大小不能超过10Mb`)
          this.$refs['refUpload'].handleRemove(image)
          return false
        }
        // 检查文件数量
        if (fileList.length > 5) {
          this.$message.error(`上传文件最大数量为5`)
          this.$refs['refUpload'].handleRemove(image)
          return false
        }
        this.dialogImageUrl = image.url
        this.dialogVisible = true
      },
      handleimg(res, image, fileList) {
        console.log('res', res)
        console.log('image', image)
        console.log('fileList', fileList)
        if (res.code === 200) {
          this.fileList = fileList
        } else {
          this.$message.error(`图片${image.name}上传失败`)
        }
      },
      //获取类别
      getClassificationList() {
        //0-互助类别，1-活动类别，2-相册类别，3-资讯类别
        classificationSelectView({ index: 0 }).then((res) => {
          if (res.code == 200) {
            this.classificationList = res.data
          } else {
            this.$baseMessage('类别列表获取失败', 'error')
          }
        })
      },
      setClassification(value) {
        this.ruleForm.helpClassification = value
      },
    },
  }
</script>
